# This function check the last gene output in the html report
function getLastReportGene
{
     chr=$1
     HTML_FILE_DIR='/home/cmbpanfs-01/yanghoch/UCSC'
     htmlFileN=$HTML_FILE_DIR/$chr/'GeneList'$chr'.htm'
     #echo $htmlFileN
     if test -s $htmlFileN; then
         lastGeneN=$(tail -n 11 $htmlFileN | head -n 1 | sed 's/<TH>//g' | sed 's/<\/TH>//g')
     else
         lastGeneN=''
     fi
     echo $lastGeneN
}

# This function get the remain gene list
function getRestGeneList 
{
     geneListFileN=$1
     lastGeneN=$2
     output=$3    
     if test -s $geneListFileN; then
         totalLine=$(wc -l $geneListFileN | cut -f 1 -d ' ')
         lastLine=$(grep -n $lastGeneN $geneListFileN | cut -f 1 -d ':')
         restGeneLineNo=$(($totalLine - $lastLine))
         echo "$totalLine"
         echo "$lastLine"         
         echo "$restGeneLineNo"
         tail -n $restGeneLineNo $geneListFileN > $output
     else
         echo "$geneListFileN not found"
     fi     
}

# This function call the previous 2 functions to get the remain genes list.
# It will continue the batchRunEnumIPerMTranSEQ
function run4RestGene
{
     chrN=$1
     lastReportGene=$(getLastReportGene $chrN)
     if [ $lastReportGene == '' ]; then
         restGeneList=$chrN'u.g'
     else
         geneList=$chrN'u.g' 
         restGeneList=$chrN'u.g.rest'
         echo "$geneList $lastReportGene $restGeneList"
         getRestGeneList $geneList $lastReportGene $restGeneList
     fi
     restGeneNo=$(wc -l $restGeneList | cut -f 1 -d ' ')
     echo "$restGeneList has $restGeneNo gene"     
     ~/SHELL/batchRunEnumIPerMTranSEQ.sh $restGeneList
}

if [ $# != 1 ]; then
    echo "This shell continue to run batchRunEnumIPerMTranSEQ.sh on the incomplete geneList chrNu.g"
    echo "It detects the last reported gene in the fixed path of HTML."
    echo "The only ptr is the chr name."
    exit
fi
chrName=$1
run4RestGene $chrName
exit

for i in {{1..22}, X, Y}; do
  cd chr$i
  echo chr$i
  run4RestGene chr$i
  cd ..
done 
